<template>
  <div class="page-content">
    <el-row :gutter="12">
      <el-col :xs="24" :sm="12" :lg="8">
        <el-input v-model="searchQuery" placeholder="部门名称" @keyup.enter="handleSearch"></el-input>
      </el-col>
      <el-col :xs="24" :sm="12" :lg="8" class="el-col2">
        <el-button v-ripple @click="handleSearch">搜索</el-button>
        <el-button @click="showDialog('add')" v-ripple>新增部门</el-button>
      </el-col>
    </el-row>

    <art-table :data="tableData" v-loading="loading" :pagination="pagination" @pagination-change="handlePageChange" row-key="id">
      <template #default>
        <el-table-column type="expand">
          <template #default="scope">
            <div class="admin-users-list">
              <div class="admin-users-header">
                <h4>部门管理员列表</h4>
                <el-button 
                  v-if="scope.row.admin_users && scope.row.admin_users.length > 0"
                  type="primary" 
                  size="small" 
                  plain
                  icon="Edit"
                  @click="showAdminDialog(scope.row)"
                >
                  管理
                </el-button>
              </div>
              <div v-if="scope.row.admin_users && scope.row.admin_users.length > 0" class="admin-users-content">
                <el-tag 
                  v-for="user in scope.row.admin_users" 
                  :key="user.id" 
                  class="admin-user-tag"
                  effect="light"
                  type="success"
                  round
                >
                  <el-icon class="admin-icon"><UserFilled /></el-icon>
                  {{ user.real_name || user.name || '未命名用户' }}
                </el-tag>
              </div>
              <div v-else class="admin-users-empty">
                <el-empty description="该部门暂无管理员" :image-size="80">
                  <template #extra>
                    <el-button type="primary" size="small" @click="showAdminDialog(scope.row)">添加管理员</el-button>
                  </template>
                </el-empty>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="sort" label="排序" sortable />
        <el-table-column label="创建时间">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="管理员" width="150">
          <template #default="scope">
            <el-tooltip
              v-if="scope.row.admin_users && scope.row.admin_users.length > 0"
              effect="dark"
              placement="top"
              :content="getAdminUsersTooltip(scope.row.admin_users)"
            >
              <el-tag size="small" type="success">
                {{ `${scope.row.admin_users.length} 位管理员` }}
              </el-tag>
            </el-tooltip>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'primary' : 'info'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200px">
          <template #default="scope">
            <button-table type="edit" @click="showDialog('edit', scope.row)" />
            <button-table type="delete" @click="deleteDepartment(scope.row)" />
            <el-tooltip content="管理部门人员" placement="top">
              <el-button
                type="success"
                circle
                size="small"
                @click="showAdminDialog(scope.row)"
              >
                <el-icon><UserFilled /></el-icon>
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </template>
    </art-table>

    <!-- 部门表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加部门' : '编辑部门'"
      width="30%"
      @closed="resetForm"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="60px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="formData.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 管理员设置对话框 -->
    <el-dialog
      v-model="adminDialogVisible"
      title="设置部门管理员"
      width="40%"
    >
      <div v-if="currentDepartment" class="admin-dialog-content">
        <div class="department-info">
          <h4>部门名称: {{ currentDepartment.name }}</h4>
        </div>
        
        <div v-loading="adminLoading" class="admin-selection">
          <div class="admin-selection-header">
            <span>选择管理员:</span>
          </div>
          
          <el-transfer
            v-model="selectedAdminIds"
            :data="allAdminUsers"
            :titles="['可选管理员', '已选管理员']"
            :props="{
              key: 'id',
              label: 'real_name'
            }"
          />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="adminDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAdminUsers" :loading="adminSubmitLoading">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ElMessageBox, ElMessage } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { ref, reactive, onMounted, computed } from 'vue'
  import { departmentService } from '@/api/departmentApi'
  import { AdminUserService } from '@/api/adminUserApi'
  import { UserFilled, Edit, Plus } from '@element-plus/icons-vue'

  // 状态变量
  const dialogType = ref('add')
  const dialogVisible = ref(false)
  const adminDialogVisible = ref(false)
  const loading = ref(false)
  const adminLoading = ref(false)
  const submitLoading = ref(false)
  const adminSubmitLoading = ref(false)
  const searchQuery = ref('')
  const tableData = ref([])
  const allAdminUsers = ref([])
  const selectedAdminIds = ref<number[]>([])
  const currentDepartment = ref<any>(null)

  // 分页配置
  const pagination = reactive({
    currentPage: 1,
    pageSize: 20,
    total: 0
  })

  // 表单数据
  const formData = reactive({
    id: null,
    name: '',
    sort: 1,
    status: 1
  })

  const formRef = ref<FormInstance>()

  // 表单验证规则
  const rules = reactive<FormRules>({
    name: [
      { required: true, message: '请输入部门名称', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    sort: [
      { required: true, message: '请输入排序号', trigger: 'blur' }
    ]
  })

  // 页面初始化时获取部门列表
  onMounted(async () => {
    await fetchDepartmentList()
    await fetchAllAdminUsers()
  })

  // 获取所有管理员用户
  const fetchAllAdminUsers = async () => {
    try {
      const res = await AdminUserService.getAllAdminUsers()
      if (res.code === 200 && Array.isArray(res.data)) {
        allAdminUsers.value = res.data.map(user => ({
          id: user.id,
          real_name: user.real_name || '未命名用户'
        }))
        console.log('获取所有管理员列表成功:', allAdminUsers.value)
      }
    } catch (error) {
      console.error('获取所有管理员列表失败:', error)
      ElMessage.error('获取管理员列表失败')
    }
  }

  // 获取部门列表
  const fetchDepartmentList = async () => {
    loading.value = true
    try {
      // 构建查询参数
      const searchParams = {}
      if (searchQuery.value.trim()) {
        searchParams['name'] = searchQuery.value.trim()
      }

      const result = await departmentService.getDepartmentList(
        pagination.currentPage,
        pagination.pageSize,
        searchParams
      )

      tableData.value = result.list || []
      pagination.total = result.total || 0
    } catch (error) {
      console.error('获取部门列表失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 搜索部门
  const handleSearch = () => {
    pagination.currentPage = 1 // 重置为第一页
    fetchDepartmentList()
  }

  // 分页变化处理
  const handlePageChange = (page: any) => {
    pagination.currentPage = page.currentPage
    pagination.pageSize = page.pageSize
    fetchDepartmentList()
  }

  // 重置表单
  const resetForm = () => {
    formData.id = null
    formData.name = ''
    formData.sort = 1
    formData.status = 1
  }

  // 显示部门对话框
  const showDialog = (type: string, row?: any) => {
    dialogType.value = type
    dialogVisible.value = true

    if (type === 'edit' && row) {
      formData.id = row.id
      formData.name = row.name
      formData.sort = row.sort || 1
      formData.status = row.status === undefined ? 1 : row.status
    } else {
      resetForm()
    }
  }

  // 显示管理员设置对话框
  const showAdminDialog = (department: any) => {
    if (!department || !department.id) {
      ElMessage.warning('部门数据不完整，无法设置管理员')
      return
    }

    currentDepartment.value = department
    adminDialogVisible.value = true
    adminLoading.value = true

    // 设置已选管理员
    if (department.admin_users && Array.isArray(department.admin_users)) {
      selectedAdminIds.value = department.admin_users.map((user: any) => user.id)
    } else {
      selectedAdminIds.value = []
    }

    adminLoading.value = false
  }

  // 保存部门管理员
  const saveAdminUsers = async () => {
    if (!currentDepartment.value || !currentDepartment.value.id) {
      ElMessage.warning('部门数据不完整，无法保存管理员设置')
      return
    }

    adminSubmitLoading.value = true
    try {
      // 判断是添加还是更新管理员
      const departmentId = currentDepartment.value.id
      const userIds = selectedAdminIds.value

      // 检查当前部门是否已有管理员
      const hasAdmins = currentDepartment.value.admin_users && 
                       currentDepartment.value.admin_users.length > 0

      if (hasAdmins) {
        // 更新管理员
        await departmentService.updateDepartmentAdmin(departmentId, userIds)
      } else {
        // 添加管理员
        await departmentService.addDepartmentAdmin(departmentId, userIds)
      }

      adminDialogVisible.value = false
      // 刷新部门列表
      await fetchDepartmentList()
      ElMessage.success('部门管理员设置成功')
    } catch (error) {
      console.error('保存部门管理员失败:', error)
    } finally {
      adminSubmitLoading.value = false
    }
  }

  // 删除部门
  const deleteDepartment = (row: any) => {
    if (!row || !row.id) {
      ElMessage.warning('无法删除，缺少部门ID')
      return
    }
    
    ElMessageBox.confirm('确定要删除该部门吗？', '删除部门', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(async () => {
      loading.value = true
      try {
        await departmentService.deleteDepartment(row.id)
        await fetchDepartmentList()
        ElMessage.success('删除部门成功')
      } catch (error) {
        console.error('删除部门失败:', error)
      } finally {
        loading.value = false
      }
    }).catch(() => {
      // 用户取消删除，不做处理
    })
  }

  // 提交表单
  const submitForm = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
      if (valid) {
        submitLoading.value = true
        try {
          // 构建提交数据
          const departmentData = {
            name: formData.name,
            sort: formData.sort,
            status: formData.status
          }

          if (dialogType.value === 'edit' && formData.id) {
            // 编辑模式
            await departmentService.updateDepartment({ 
              ...departmentData, 
              id: formData.id 
            })
          } else {
            // 添加模式
            await departmentService.addDepartment(departmentData)
          }

          dialogVisible.value = false
          await fetchDepartmentList()
        } catch (error) {
          console.error(`${dialogType.value === 'add' ? '添加' : '编辑'}部门失败:`, error)
        } finally {
          submitLoading.value = false
        }
      }
    })
  }

  // 格式化日期
  const formatDate = (date: string) => {
    if (!date) return '-'
    
    try {
      return new Date(date)
        .toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        })
        .replace(/\//g, '-')
    } catch (error) {
      return date
    }
  }

  // 获取管理员用户提示文本
  const getAdminUsersTooltip = (adminUsers: any[]): string => {
    if (!adminUsers || adminUsers.length === 0) {
      return '暂无管理员'
    }
    
    // 最多显示5个管理员名称
    const displayUsers = adminUsers.slice(0, 5)
    const userNames = displayUsers.map((user: any) => {
      // 尝试从real_name或name中获取用户名称
      return user.real_name || user.name || '未命名用户'
    })
    
    let tooltipText = userNames.join('、')
    
    // 如果有更多管理员，显示省略号
    if (adminUsers.length > 5) {
      tooltipText += `...等共 ${adminUsers.length} 位管理员`
    }
    
    return tooltipText
  }
</script>

<style lang="scss" scoped>
  .page-content {
    .svg-icon {
      width: 1.8em;
      height: 1.8em;
      overflow: hidden;
      vertical-align: -8px;
      fill: currentcolor;
    }
    
    .el-col2 {
      display: flex;
      gap: 10px;
      margin-top: 12px;
      
      @media (min-width: 768px) {
        margin-top: 0;
      }
    }
  }
  
  .dialog-footer {
    padding-top: 10px;
    text-align: right;
  }

  .admin-users-list {
    padding: 20px;
    background-color: var(--el-fill-color-light);
    border-radius: 8px;
    margin: 12px 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    transition: all 0.3s;

    &:hover {
      box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
    }

    .admin-users-header {
      margin-bottom: 15px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid var(--el-border-color-light);
      padding-bottom: 12px;
      
      h4 {
        margin: 0;
        font-size: 16px;
        font-weight: bold;
        color: var(--el-text-color-primary);
        display: flex;
        align-items: center;
        
        &:before {
          content: '';
          display: inline-block;
          width: 4px;
          height: 16px;
          background-color: var(--el-color-primary);
          margin-right: 8px;
          border-radius: 2px;
        }
      }
    }

    .admin-users-content {
      display: flex;
      flex-wrap: wrap;
      gap: 12px;
      
      .admin-user-tag {
        margin-right: 0;
        margin-bottom: 0;
        padding: 6px 12px;
        font-size: 13px;
        display: flex;
        align-items: center;
        transition: all 0.3s;
        cursor: default;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
        }
        
        .admin-icon {
          margin-right: 5px;
          font-size: 14px;
        }
      }
    }

    .admin-users-empty {
      color: var(--el-text-color-secondary);
      font-size: 13px;
      padding: 20px 0;
      display: flex;
      justify-content: center;
    }
  }

  .admin-dialog-content {
    .department-info {
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px dashed var(--el-border-color);
      
      h4 {
        margin: 0;
        font-size: 16px;
        font-weight: bold;
        color: var(--el-text-color-primary);
        display: flex;
        align-items: center;
        
        &:before {
          content: '';
          display: inline-block;
          width: 4px;
          height: 16px;
          background-color: var(--el-color-primary);
          margin-right: 8px;
          border-radius: 2px;
        }
      }
    }

    .admin-selection {
      &-header {
        margin-bottom: 15px;
        font-weight: bold;
        color: var(--el-text-color-primary);
      }
    }
  }

  :deep(.el-transfer) {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .el-transfer-panel {
      width: 45%;
      border-radius: 8px;
      
      .el-transfer-panel__header {
        background-color: var(--el-color-primary-light-9);
        border-top-left-radius: 8px;
        border-top-right-radius: 8px;
      }
    }
    
    .el-transfer__buttons {
      padding: 0 15px;
    }
  }
</style>
